<?php
function getRace($id) {
    global $races;
    if (isset($id)) {
    	return $races[$id];
    }
}

function loadRaces() {
    $races = array ();
    $rs = executeQuery("select r.race_id, r.name, r.reroll_cost, r.comments, rrs.fk_rule_id from races r, races_rule_sets rrs where r.race_id=rrs.fk_race_id order by r.name, rrs.fk_rule_id");
    while ($row = mysql_fetch_row($rs)) {
        $race = new Race();
        $race->init($row);
        $races[$race->id]=$race;
    }
    /* Load "similar" races */
    foreach($races as $race) {
	    $rs = executeQuery("select r.race_id from races r where r.race_id<>$race->id and r.name like '$race->name'");
	    while ($row = mysql_fetch_row($rs)) {
	    	array_push($race->similar, $row[0]);
        }
    }
    return $races;
}

class Race {
    var $id;
    var $name;
    var $rerollCost;
    var $positions;
    var $comments;
    private $ruleId;
    var $similar;

    function Race() {
    	$this->similar = array();
    }

    function init($row) {
        $i = 0;
        $this->id = $row[$i++];
        $this->name = $row[$i++];
        $this->rerollCost = $row[$i++];
        $this->comments = $row[$i++];
        $this->ruleId = $row[$i++];

        $this->positions = array ();
        $rs = executeQuery("select position_id, position, ma, st, ag, av, qty, cost from positions, races_positions where fk_race_id=$this->id and fk_position_id=position_id order by cost asc, qty desc, position");
        while ($row = mysql_fetch_row($rs)) {
            $position = new Position();
            $position->init($row);
            $this->positions[$position->id] = $position;
        }
        uasort($this->positions, "positionSort");
        return $this;
    }
    
    /**
     * returns the rule set this race is valid for
     */
    function getRuleId() {
        return $this->ruleId;
    }
    
    function getRaceDisplay() {
        return $this->name . " (" . $this->getShortRuleSetName() . ")";
    }
    
    function getShortRuleSetName() {
    	global $ruleSets;
    	return $ruleSets[$this->ruleId]->getShortName();
    }

    function getPosition($positionStr) {
        foreach ($this->positions as $position) {
            if (0 == strcasecmp($position->position, $positionStr)) {
                return $position;
            }
        }

        return false;
    }

    function getPositionById($id) {
    	return $this->positions[$id];
    }
}
?>